angular.module('epApp.controllers')
  .controller('HomeCtrl', function ($scope, $ionicLoading, $rootScope, $location, $stateParams, $window, $state, $ionicPopup, $ionicModal, SearchHist, User,$timeout, $cordovaGeolocation) {

    $scope.isCome = false;
    $scope.isFocus = false;

    function getFocus() {
      $scope.isFocus = true;
      $scope.isCome = true;
    };

    $scope.setBlur = function () {
      $scope.isFocus = false;
    }


    $scope.Max = 10000;
    //Place中存有lat,lng
    $scope.Place = {};
    $scope.SearchPlace = {};
    //停车筛选页的参数
    $scope.ParkOption = {};
    $scope.Route = {};
    //当前停车场
    $scope.NowPark = {};
    $scope.ParkPrice = {};
    $scope.ParkPrice.ChargeList = [];
    //附近停车场
    $scope.NearPark = {};
    $scope.NearPark.On = {};
    $scope.NearPark.Off = {};
    $scope.NearPark.Filter = {};

    $scope.NearPark.markers = [];

    $scope.User = {};
    $scope.UserSet = {};
    $scope.Com = {};
    $scope.NowTime = {};
    $scope.HotCom = [];
    $scope.NewCom = [];
    $scope.data1 = [];
    $scope.data2 = [];
    $scope.Collect = 0;

    ///********初始化**********///
    $scope.$on('$ionicView.enter', function () {

      if ($stateParams.userName) {
        if($stateParams.loginType=='Email') {
          getUser($stateParams.userName);
          console.log($stateParams.userName);
          document.getElementById('userItem').style.display='block';
          document.getElementById('user').innerHTML=$stateParams.userName;
          document.getElementById('login').innerHTML='注销账号';
        }
        else if($stateParams.loginType=='Wechat'){
          console.log('微信用户');
          getWechatUser($stateParams.userName);
        }

        console.log('登录用户');
        console.log($scope.User);
      }else {
        document.getElementById('login').innerHTML='请登陆';
        document.getElementById('user').innerHTML='用户';
        document.getElementById('userItem').style.display='none';
      }
      init();
      initSearchShow();
      initParkShow();
      initParkFitlerShow();
      initPComDetailShow();
      initPNewComDetailShow();
      initPComShow();
      initClickParkShow();
    });



    /********主页面的操作********/
    //点击定位按钮
    $scope.getLocation = function () {
      getLocation();
    };
    //点击附近停车场按钮
    $scope.showParkInList = function () {
      //显示停车场列表页
      if ($scope.NearPark.Filter.Parks.length > 0) {
        $scope.parkModal.show();
      } else {
        $rootScope.showToastOrDialog('附近暂无符合条件的停车场', function () {
        });
      }
    };
    //点击时间筛选
    $scope.showParkTimeFilter = function () {
      document.getElementById('timeFilter').style.display = "block";
    };
    //取消时间筛选
    $scope.closeParkTimeFilter = function () {
      document.getElementById('timeFilter').style.display = "none";
    };
    //设置停车时间
    $scope.setParkTime = setParkTime;

    //点击详细筛选
    $scope.showParkFilter = function () {
      var d = new Date();
      $scope.ParkOption.EnterTime = d.getHours() + ':' + d.getMinutes();
      $scope.ParkOption.LeaveTime = d.getHours() + ':' + d.getMinutes();

      $scope.ParkOption.EnterData = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
      $scope.ParkOption.LeaveData = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();

      $scope.ParkOption.Enter = $scope.ParkOption.EnterData + ' ' + $scope.ParkOption.EnterTime;
      $scope.ParkOption.Leave = $scope.ParkOption.LeaveData + ' ' + $scope.ParkOption.LeaveTime;
      $scope.ParkOption.Enter = $scope.ParkOption.Enter.replace(/-/g, "/");
      $scope.ParkOption.Leave = $scope.ParkOption.Leave.replace(/-/g, "/");
      $scope.ParkOption.TotalTime = "0天" + "0小时" + "0分钟";

      $scope.parkFilterModal.show();
    };

    //点击搜索输入框
    $scope.clickSearchInput = function () {
      getHistory();
      $scope.$broadcast('newItemAdded');

      $scope.searchModal.show();
      getFocus();
    };
    //导航到停车位
    $scope.directPark = function (park) {
      //document.getElementById('localInfo').style.display = "none";
      document.getElementById('parkInfo').style.display = "none";
      $scope.parkModal.hide();
      $scope.searchModal.hide();
      closePDesc();

      $scope.latlng = [];
      $scope.latlng = park.location.split(",");
      directPLat($scope.Place.lat, $scope.Place.lng, park);

      $scope.Route.end = $scope.latlng[1] + ',' + $scope.latlng[0];
      $scope.Route.start = $scope.Place.lat + ',' + $scope.Place.lng;
      console.log($scope.Route.start);
      console.log($scope.Route.end);

      ArrivalOrNot(park);
      GoToGoogle($scope.Route.start, $scope.Route.end);
    };

    //点击关闭地址card
    $scope.closeLocalInfo = function () {
      document.getElementById('localInfo').style.display = "none";
    };

    //点击关闭停车场card
    $scope.closeParkInfo = function () {
      document.getElementById('parkInfo').style.display = "none";
    };

    /*******搜索页面操作********/

    //点击搜索按钮或列表中的地址
    $scope.search = search;
    //输入框输入文字
    $scope.onSearchModal = function (data) {
      $scope.searchConifg.showCancel = !(data && data.length > 0);
      AutoComplete(data);
    };
    //点击取消，关闭弹出框
    $scope.closeSearch = function () {
      $scope.searchModal.hide();
    };
    //点击列表中的停车场
    $scope.showParkDesc = showParkDesc;

    /*******停车场列表页的操作********/

    ///关闭附近停车场弹出框
    $scope.closeParkShow = function () {
      $scope.parkModal.hide();
    };
    $scope.sortByPrice=function(){
      $scope.NearPark.Filter.Parks.sort(function(a,b){
        return a.price- b.price||$scope.NearPark.Filter.Parks.indexOf(a)-$scope.NearPark.Filter.Parks.indexOf(b);
      });
      document.getElementById('priceBtn').style.color='white';
      document.getElementById('priceBtn').style.background='#1E3DA1';
      document.getElementById('distanceBtn').style.color='#1E3DA1';
      document.getElementById('distanceBtn').style.background='';
    };
    $scope.sortByDistance=function(){
      $scope.NearPark.Filter.Parks.sort(function(a,b){
        return a.distance- b.distance||$scope.NearPark.Filter.Parks.indexOf(a)-$scope.NearPark.Filter.Parks.indexOf(b);
      });
      document.getElementById('distanceBtn').style.color='white';
      document.getElementById('distanceBtn').style.background='#1E3DA1';
      document.getElementById('priceBtn').style.color='#1E3DA1';
      document.getElementById('priceBtn').style.background='';
    };

    /*******停车场详情页操作********/
    $scope.closePDesc = closePDesc;
    $scope.ChangeCollect = ChangeCollect;
    ///点击评价，弹出评价详情
    $scope.PComDe = PComDe;
    $scope.closeClickParkDetial = function () {
      $scope.ClickparkModal.hide();
    };

    /*******热门评论详情页操作*******/
    ///弹出最新评论页
    $scope.pNewComShow = function () {
      $scope.PNewComDetailModal.show();
      $scope.PComDetailModal.hide();
    };
    ///弹出评论编辑页
    $scope.pComEdit = function () {
      $scope.staract = 0;
      $scope.Praise = '0';
      $scope.com = {};
      $scope.PComModal.show();
    };

    /*******最新评论详情页操作*******/
    ///关闭评论详情页
    $scope.closePComDetial = function () {
      $scope.PComDetailModal.hide();
      $scope.PNewComDetailModal.hide();
    };
    ///弹出热门评论页
    $scope.pHotComShow = function () {
      $scope.PComDetailModal.show();
      $scope.PNewComDetailModal.hide();

    };
    ///弹出评论编辑页
    $scope.pComEdit = function () {
      $scope.staract = 0;
      $scope.Praise = '0';
      $scope.com = {};
      $scope.PComModal.show();
    };

    /********评论编辑页操作******/
    ///关闭评论编辑页
    $scope.closePCom = function () {
      $scope.PComModal.hide();
    };

    ///保存用户停车场评论信息
    $scope.savePCom = function () {
      $scope.PComModal.hide();
      $scope.PNewComDetailModal.hide();
      $scope.PComDetailModal.hide();
      saveParkCom();
    };

    /***********停车选项页操作**********/
    $scope.closeParkFilter = function () {
      $scope.parkFilterModal.hide();
    };
    //点击保存筛选条件按钮
    $scope.saveParkFilter = function () {

      $scope.UserSet.TotalTime = $scope.ParkOption.TotalTime;
      $scope.UserSet.EnterTime = $scope.ParkOption.Enter;
      $scope.UserSet.LeaveTime = $scope.ParkOption.Leave;
      //第一位表示街边停车场，第二位表示非街边停车场
      if (document.getElementById('streetPark').checked && document.getElementById('nomalPark').checked) {
        $scope.UserSet.ParkType = 11;
      } else if (!document.getElementById('streetPark').checked && document.getElementById('nomalPark').checked) {
        $scope.UserSet.ParkType = 01;
      } else if (document.getElementById('streetPark').checked && !document.getElementById('nomalPark').checked) {
        $scope.UserSet.ParkType = 10;
      } else if (!document.getElementById('streetPark').checked && !document.getElementById('nomalPark').checked) {
        $scope.UserSet.ParkType = 00;
      }
      $scope.parkFilterModal.hide();

      FilteParks();


    };

    $scope.showTimeSelect = function (type) {
      $scope.NowTime.hours = new Date().getHours();
      $scope.NowTime.minutes = new Date().getMinutes();
      $scope.Type = type;
      popTime();
    };
    $scope.closeTimeSelector = function () {
      $scope.timePopup.close();
    };
    $scope.setEnter = function () {
      $scope.DateType = 'enter';
    };
    $scope.setLeave = function () {
      $scope.DateType = 'leave';
    };
    $scope.setEnterTime = function () {
      $scope.timestr = $scope.NowTime.hours + ':' + $scope.NowTime.minutes;
      if ($scope.Type == 'enter') {
        $scope.ParkOption.EnterTime = $scope.timestr;
      } else {
        $scope.ParkOption.LeaveTime = $scope.timestr;
      }
      $scope.timePopup.close();
      calculateParkTime();
    };
    $scope.addHours = function () {
      if ($scope.NowTime.hours < 23) {
        $scope.NowTime.hours = $scope.NowTime.hours + 1;
      } else {
        $scope.NowTime.hours = 0;
      }
    };
    $scope.addMinutes = function () {
      if ($scope.NowTime.minutes < 59) {
        $scope.NowTime.minutes = $scope.NowTime.minutes + 1;
      } else {
        $scope.NowTime.minutes = 0;
      }
    };

    $scope.cutHours = function () {
      if ($scope.NowTime.hours > 0) {
        $scope.NowTime.hours = $scope.NowTime.hours - 1;
      } else {
        $scope.NowTime.hours = 23;
      }
    };
    $scope.cutMinutes = function () {
      if ($scope.NowTime.minutes > 0) {
        $scope.NowTime.minutes = $scope.NowTime.minutes - 1;
      } else {
        $scope.NowTime.minutes = 59;
      }
    };


    ///时间选择器
    function popTime() {
      $scope.timePopup = $ionicPopup.show({
        title: '选择时间',
        templateUrl: "templates/home/timeSelector.html",
        scope: $scope,
      });
      $scope.timePopup.then(function (res) {
        if (res) {
        } else {
        }
      });
    };

    ///点亮星星函数
    $scope.light = function (data) {
      $scope.staract = data;
      $scope.star = document.getElementById('star');
      for (i = 0; i < data; i++) {
        var starname = 'star' + i;
        document.getElementById(starname).className = 'act';
      }
      for (i = data; i < 5; i++) {
        var starname = 'star' + i;
        document.getElementById(starname).className = 'off';
      }
    };

    ///地图初始化
    function init() {
      $ionicLoading.show({
        content: '地图加载中...'
      });
      $scope.initMap();
    };

    $scope.initMap = function () {
      $timeout(function () {
        var isLoaded = parseInt(window.localStorage.getItem('google_js_lib_loaded'));
        console.log(isLoaded);
        if (!isLoaded) {
          $scope.initMap();
          console.log('cannot  initMap isLoaded:' + isLoaded);
        } else {
          console.log('can initMap isLoaded:' + isLoaded);
          $ionicLoading.hide();

          //初始化 地图
          $scope.map = new google.maps.Map(document.getElementById('map'), {
            zoom: 15,
            center: {lat: 42.3600825, lng: -71.05888010000001},
            disableDefaultUI: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          });
          getLocation();
          //findNearPark(42.3600825, -71.05888010000001);
          $scope.SearchPlace.lat = 42.3600825;
          $scope.SearchPlace.lng = -71.05888010000001;
          //初始化导航
          $scope.directionsService = new google.maps.DirectionsService;
          $scope.directionsDisplay = new google.maps.DirectionsRenderer;
          $scope.marker = new google.maps.Marker;
          $scope.marker.setMap($scope.map);
          $scope.directionsDisplay.setMap($scope.map);

          //对zoom_changed添加监听事件
          ZoomChangedListen();
        }
      }, 1000);
    };

    ///初始化搜索记录弹出框
    function initSearchShow() {
      // 初始化 搜索弹出框
      $ionicModal.fromTemplateUrl(
        "templates/home/searchHist.html",
        function (modal) {
          $scope.searchModal = modal;
        },
        {
          scope: $scope,
          animation: 'slide-in-up'
        });
      $scope.searchConifg = {showCancel: true};
      $scope.searchPlace = '';

    };

    ///初始化附近停车场弹出框
    function initParkShow() {
      // 初始化 搜索弹出框
      $ionicModal.fromTemplateUrl(
        "templates/home/Parkdetail.html",
        function (modal1) {
          $scope.parkModal = modal1;
        },
        {
          scope: $scope,
          animation: 'slide-left-right'
        });
    };

    ///初始化停车场详情弹出框
    function initClickParkShow() {
      // 初始化 搜索弹出框
      $ionicModal.fromTemplateUrl(
        "templates/home/ClickParkDetail.html",
        function (modal1) {
          $scope.ClickparkModal = modal1;
        },
        {
          scope: $scope,
          animation: 'slide-left-right'
        });
    };


    ///初始化Filter弹出框
    function initParkFitlerShow() {
      $ionicModal.fromTemplateUrl(
        "templates/home/ParkFilter.html",
        function (modal1) {
          $scope.parkFilterModal = modal1;
        },
        {
          scope: $scope,
          animation: 'slide-left-right'
        });
    };

    ///初始化热门评论详情弹出框
    function initPComDetailShow() {
      // 初始化 搜索弹出框
      $ionicModal.fromTemplateUrl(
        "templates/home/PComDetail.html",
        function (modal1) {
          $scope.PComDetailModal = modal1;
        },
        {
          scope: $scope,
          animation: 'slide-left-right'
        });
    };

    ///初始化最新评论详情弹出框
    function initPNewComDetailShow() {
      // 初始化 搜索弹出框
      $ionicModal.fromTemplateUrl(
        "templates/home/PNewComDetail.html",
        function (modal1) {
          $scope.PNewComDetailModal = modal1;
        },
        {
          scope: $scope,
          animation: 'slide-left-right'
        });
    };

    ///初始化评论编辑弹出框
    function initPComShow() {
      // 初始化 搜索弹出框
      $ionicModal.fromTemplateUrl(
        "templates/home/ParkCom.html",
        function (modal1) {
          $scope.PComModal = modal1;
        },
        {
          scope: $scope,
          animation: 'slide-left-right'
        });
    };

    ///设置停车时间
    function setParkTime(time) {
      document.getElementById('timeFilter').style.display = "none";
      var d = new Date();
      $scope.ParkOption.EnterTime = d.getHours() + ':' + d.getMinutes();
      $scope.ParkOption.EnterData = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();

      if (d.getHours() + time > 23) {
        $scope.ParkOption.LeaveTime = (d.getHours() + time - 24) + ':' + d.getMinutes();
        $scope.ParkOption.LeaveData = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + (d.getDate() + 1);
      } else {
        $scope.ParkOption.LeaveTime = (d.getHours() + time) + ':' + d.getMinutes();
        $scope.ParkOption.LeaveData = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
      }
      $scope.ParkOption.Enter = $scope.ParkOption.EnterData + ' ' + $scope.ParkOption.EnterTime;
      $scope.ParkOption.Leave = $scope.ParkOption.LeaveData + ' ' + $scope.ParkOption.LeaveTime;
      $scope.ParkOption.Enter = $scope.ParkOption.Enter.replace(/-/g, "/");
      $scope.ParkOption.Leave = $scope.ParkOption.Leave.replace(/-/g, "/");
      $scope.ParkOption.WholeEnterTime = new Date($scope.ParkOption.Enter);
      $scope.ParkOption.WholeLeaveTime = new Date($scope.ParkOption.Leave);
      calculateTime();

      $scope.UserSet.TotalTime = $scope.ParkOption.TotalTime;
      $scope.UserSet.EnterTime = $scope.ParkOption.Enter;
      $scope.UserSet.LeaveTime = $scope.ParkOption.Leave;

      FilteParks();
    }

    ///获取用户信息
    function getUser(user_email) {
      SearchHist.getUserInfo(user_email)
        .then(function (data) {
          $scope.User = data.data;
          document.getElementById('user').innerHTML=$scope.User.nick_name;
        }, function (error) {
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    ///获取微信用户信息
    function getWechatUser(user_UnionId){
      User.wechatLogin( '',user_UnionId)
        .then(function (data) {
          $scope.User = data.data;

          console.log(data.data);
        }, function (error) {
          console.log(error);
          //$rootScope.showToastOrDialog(error.data.msg, function () {
          //
          //});
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    }

    ///根据user_id查找用户信息
    function getUserById(user_id) {
      SearchHist.getUserByID(user_id)
        .then(function (data) {
          return data.data.first_name;
        }, function (error) {
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    ///定位
    function getLocation() {

      var posOptions = {timeout: 10000, enableHighAccuracy: false};
      $cordovaGeolocation
        .getCurrentPosition(posOptions)
        .then(function (position) {
          $scope.map.setCenter({lat: position.coords.latitude, lng: position.coords.longitude});
          $scope.image = {
            url: 'img/mylocation.png',
          };
          $scope.marker = new google.maps.Marker({
            icon: $scope.image,
            map: $scope.map,
            position: {lat: position.coords.latitude, lng: position.coords.longitude}
          });
          $scope.Place.lat = position.coords.latitude;
          $scope.Place.lng = position.coords.longitude;

          console.log('latlngChanged');

          $scope.SearchPlace.lat = position.coords.latitude;
          $scope.SearchPlace.lng = position.coords.longitude;

          findNearPark(position.coords.latitude, position.coords.longitude);

        }, function (err) {
        });
      document.getElementById('localInfo').style.display = "none";
      document.getElementById('parkInfo').style.display = "none";
    };

    ///搜索目的地
    function search(data) {
      $scope.marker.setMap(null);
      $scope.directionsDisplay.setMap(null);
      //保存此次地址搜索记录
      saveSearch($scope.User.user_id, data);
      //关闭弹出框
      $scope.searchModal.hide();
      //开始搜索
      $scope.Place.search = data;
      document.getElementById('localInfo').style.display = "block";
      document.getElementById('parkInfo').style.display = "none";
      $scope.geocoder = new google.maps.Geocoder;
      $scope.map.setZoom(15);
      $scope.geocoder.geocode({'address': data}, function (results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          $scope.map.setCenter(results[0].geometry.location);
          $scope.Place.formatted_address = results[0].formatted_address;
          //获取当前位置的经纬度
          $scope.Currentlat = results[0].geometry.location.toJSON().lat;
          $scope.Currentlng = results[0].geometry.location.toJSON().lng;
          console.log($scope.Currentlat);
          console.log($scope.Currentlng);

          $scope.SearchPlace.lat = parseFloat(results[0].geometry.location.toJSON().lat);
          $scope.SearchPlace.lng = parseFloat(results[0].geometry.location.toJSON().lng);

          findNearPark($scope.Currentlat, $scope.Currentlng);
          $scope.image = {
            url: 'img/mylocation.png',
          };
          $scope.marker = new google.maps.Marker({
            icon:$scope.image,
            map: $scope.map,
            position: results[0].geometry.location
          });
        } else {
          $rootScope.showToastOrDialog('Geocode was not successful for the following reason:' + status, function () {
          });
        }
      });
      $rootScope.showToastOrDialog('搜索' + data, function () {
      });
    };

    ///搜索某一停车场,并显示停车场详情
    function showParkDesc(park) {
      //$scope.marker.setMap(null);
      //$scope.directionsDisplay.setMap(null);
      //保存此次停车场搜索记录
      saveParkSearch($scope.User.user_id, park.park_id);
      $scope.NowPark = park;
      //关闭弹出框
      $scope.searchModal.hide();
      $scope.parkModal.hide();

      $scope.ClickparkModal.show();

      CollectOrNot($scope.User.user_id, park.park_id, 'park');

      //收费信息
      if (park.type == 'Parking Meter') {
        getOnStreetChargeRule(park);
      } else {
        getOffStreetChargeRule(park.park_id);
      }

      $scope.latlng = [];
      $scope.latlng = park.location.split(",");
      findNearPark(parseFloat($scope.latlng[1]), parseFloat($scope.latlng[0]));
      //$scope.map.setZoom(15);
      //$scope.map.panTo({lng: parseFloat($scope.latlng[0]+0.25), lat: parseFloat($scope.latlng[1] )});
      // $scope.map.panTo({lng: parseFloat($scope.latlng[0]), lat: parseFloat($scope.latlng[1]-0.015)});
      //显示详情页
      showParkDescHtml();
      Star($scope.NowPark.park_id);//显示停车场评价星级
    };

    ///查找 附近停车场
    function findNearPark(lat, lng) {
      SearchHist.fdetail(lat, lng)
        .then(function (data) {
          $scope.Park = [];
          $scope.Park = data;
          //把查找到的停车场存放在NearPark.Parks中，并把这些停车场归类
          initNearParks();
          $scope.NearPark.Parks = data.data;
          initFilterParks();
          ReclassParks($scope.NearPark.Parks);
          addAdoptMarker('0');
        }, function (error) {
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    }


    ///从当前位置（Latlng）导航到停车场
    function directPLat(Lat, Lng, park) {
      //清空地图上的marker
      $scope.marker.setMap(null);
      $scope.directionsDisplay.setMap(null);
      $scope.geocoder = new google.maps.Geocoder;
      $scope.geocoder.geocode({'location': {lat: Lat, lng: Lng}}, function (results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          $scope.testPlace = results[1].formatted_address;
        }
        ;
      });
      //关闭弹出框
      $scope.searchModal.hide();
      //开始导航
      $scope.Place.destination = park.name;
      $scope.latlng = [];
      $scope.latlng = park.location.split(",");

      $scope.directionsDisplay.setMap($scope.map);
      $scope.parkLat = new google.maps.LatLng(parseFloat($scope.latlng[1]), parseFloat($scope.latlng[0]));
      $scope.directionsService.route({
        origin: {lat: Lat, lng: Lng},
        destination: $scope.parkLat,
        travelMode: google.maps.TravelMode.DRIVING
      }, function (response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
          $scope.directionsDisplay.setDirections(response);
        } else {
          $rootScope.showToastOrDialog('Directions request failed due to ' + status, function () {
          });
        }
      });
      $rootScope.showToastOrDialog('从您的位置导航到' + park.name, function () {
      });


    };

    ///保存用户搜索记录
    function saveSearch(user_id, search_value) {
      SearchHist.saveSearch(user_id, search_value)
        .then(function (data) {
          // search(searchPlace);
        }, function (error) {
          console.log(error);
          $rootScope.showToastOrDialog(error.msg, function () {
          });
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    ///保存用户停车场搜索记录
    function saveParkSearch(user_id, search_value) {
      SearchHist.saveParkSearch(user_id, search_value)
        .then(function (data) {

        }, function (error) {
          console.log(error);
          $rootScope.showToastOrDialog(error.data.msg, function () {
          });
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    ///保存用户POI搜索记录
    function savePOISearch(user_id, search_value) {
      SearchHist.savePOISearch(user_id, search_value)
        .then(function (data) {

        }, function (error) {
          console.log(error);
          $rootScope.showToastOrDialog(error.data.msg, function () {
          });
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    ///获取用户搜索记录
    function getHistory() {
      $scope.data1 = [];
      $scope.data2 = [];
      SearchHist.searchHist($scope.User.user_id)
        .then(function (data) {
          console.log($scope.User.user_id);
          $scope.park = data;
          $scope.park.data.forEach(function (data) {
            if (data.search_type == 'address') {
              $scope.data1.push(data);
            }
            else if (data.search_type == 'park') {
              getParkInfo(data.search_value);
            }
          });
        }, function (error) {
          console.log(error);
          $rootScope.showToastOrDialog(error.data.msg, function () {
          });
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    ///根据停车场id获取停车场信息
    function getParkInfo(parkID) {
      SearchHist.getParkByID(parkID)
        .then(function (data) {
          $scope.User.ParkHistory = data.data;
          $scope.User.ParkHistory.forEach(function (data) {
            $scope.data2.push(data);
          });
        }, function (error) {
          console.log(error);
          $rootScope.showToastOrDialog(error.data.msg, function () {
          });
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    }

    ///查询用户是否收藏
    function CollectOrNot(user_id, search_value, search_type) {
      SearchHist.getCollectOrNot(user_id, search_value, search_type)
        .then(function (data) {
          console.log(data);
          if (data.data.code != '-1') {
            //有值存在则星星为黄色
            $scope.star = document.getElementById("Collect");
            $scope.star.style.color = "orange";
            $scope.Collect = 1;
          }
        }, function (error) {

          console.log(error);
          $scope.star = document.getElementById("Collect");
          $scope.star.style.color = "#1E3DA1";
          $scope.Collect = 0;
          //$rootScope.showToastOrDialog(error.data.msg, function () {
          //});
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    }

    ///显示停车场摘要
    function showParkBrief(name) {

      $scope.NearPark.Filter.Parks.forEach(function (data) {
        if (data.name == name) {
          $scope.Place.clickPark = data;
        }
      });
      // console.log("+++++++++++++++"+$scope.Place.clickPark.location);
      document.getElementById('localInfo').style.display = "none";
      document.getElementById('parkInfo').style.display = "block";
      $scope.$apply();

    };

    ///点击删除或添加收藏
    function ChangeCollect(park, search_type) {
      if ($scope.Collect) {
        deleteCollect($scope.User.user_id, park.park_id, search_type);
      } else {
        insertCollect($scope.User.user_id, park.park_id, search_type);
      }
    };

    ///删除收藏
    function deleteCollect(user_id, search_values, search_type) {
      SearchHist.deleteCollect(user_id, search_values, search_type)
        .then(function (data) {
          $scope.Collect = 0;
          $rootScope.showToastOrDialog('删除收藏成功!', function () {
          });
          $scope.star = document.getElementById("Collect");
          $scope.star.style.color = "#666666";
        }, function (error) {
          console.log(error);
          //$rootScope.showToastOrDialog(error.data.msg, function () {
          //});
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };
    ///添加收藏
    function insertCollect(user_id, search_values, search_type) {
      SearchHist.insertCollect(user_id, search_values, search_type)
        .then(function (data) {
          $scope.Collect = 1;
          $rootScope.showToastOrDialog('收藏成功!', function () {
          });
          $scope.star = document.getElementById("Collect");
          $scope.star.style.color = "orange";

        }, function (error) {
          console.log(error);
          //$rootScope.showToastOrDialog(error.data.msg, function () {
          //});
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    ///输入框自动补全
    function AutoComplete(data) {
      ///搜索框自动补全
      var displaySuggestions = function (predictions, status) {
        if (status != google.maps.places.PlacesServiceStatus.OK) {
          alert(status);
          return;
        }
        $scope.result = [];
        predictions.forEach(function (prediction) {
          $scope.result.push(prediction.description);
        });
        //  console.log($scope.result);
      };
      var service = new google.maps.places.AutocompleteService();
      service.getPlacePredictions({input: data, types: ['geocode', 'establishment']}, displaySuggestions);
    };

    ///添加marker
    function addMarker(feature) {
      //TODO
      // 要自定义图标
      var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
      var icons = {
        parking: {
          icon: iconBase + 'parking_lot_maps.png'
        },
        library: {
          icon: iconBase + 'library_maps.png'
        },
        info: {
          icon: iconBase + 'info-i_maps.png'
        }
      };
      $scope.marker = new google.maps.Marker({
        position: feature.position,
        icon: icons[feature.type].icon,
        map: $scope.map,
        title: feature.Name,
      });
      $scope.marker.addListener('click', function () {
        showParkBrief(feature.Name);
      });
    };

    //addAdoptMarker
    function addAdoptMarker(markerLevel) {
      $scope.NearPark.markers.forEach(function (data) {
        data.setMap(null);
      });
      $scope.NearPark.markers = [];
      if (markerLevel < 2) {
        //第一个级别
        if (markerLevel == '0') {
          $scope.image = {
            url: 'img/park_small.png',
            // This marker is 20 pixels wide by 32 pixels high.
            size: new google.maps.Size(40, 30.4),
            // The origin for this image is (0, 0).
            origin: new google.maps.Point(0, 0),
            // The anchor for this image is the base of the flagpole at (0, 32).
            anchor: new google.maps.Point(0, 32)
          };
          drawParkLot($scope.NearPark.Filter.Easy, 'Polyline', 'green');
          drawParkLot($scope.NearPark.Filter.Middle, 'Polyline', 'orange');
          drawParkLot($scope.NearPark.Filter.Difficult, 'Polyline', 'red');
          drawPoint($scope.NearPark.Filter.OffParks, $scope.image, 0);
          //drawParkLot($scope.NearPark.Filter.OnParks, 'Polyline', 'green');

        }
        //第二个级别
        else if (markerLevel == '1') {
          $scope.image = {
            url: 'img/park_price.png',
            // This marker is 20 pixels wide by 32 pixels high.
            size: new google.maps.Size(40, 30.4),
            // The origin for this image is (0, 0).
            origin: new google.maps.Point(0, 0),
            // The anchor for this image is the base of the flagpole at (0, 32).
            anchor: new google.maps.Point(0, 32)
          };
          drawPoint($scope.NearPark.Filter.OffParks, $scope.image, 1);
          drawParkLot($scope.NearPark.Filter.Easy, 'Polyline', 'green');
          drawParkLot($scope.NearPark.Filter.Middle, 'Polyline', 'orange');
          drawParkLot($scope.NearPark.Filter.Difficult, 'Polyline', 'red');
        }

      }
      //第三个级别
      else if (markerLevel == '2') {
        drawParkLot($scope.NearPark.Filter.Easy, 'Polyline', 'green');
        drawParkLot($scope.NearPark.Filter.Middle, 'Polyline', 'orange');
        drawParkLot($scope.NearPark.Filter.Difficult, 'Polyline', 'red');
        // drawParkSpace($scope.NearPark.Filter.ParkSpace);
        drawParkLot($scope.NearPark.Filter.OffParks, 'Polygon', 'blue');
        drawParkEntity($scope.NearPark.Filter.ParkEntity);
      }
    }

    //显示停车场详情
    function showParkDescHtml() {
      $scope.ClickparkModal.show();
    };

    ///取消显示停车场详细信息，返回主页
    function closePDesc(Parklatlng) {
      $scope.ClickparkModal.hide();
    };

    ///点亮星星数据
    function Star(park_id) {
      //获取评价分数
      SearchHist.fmark(park_id)
        .then(function (data) {
          //获取分数，以星星显示
          $scope.j = 0;
          if (data.data[0].avg_mark != null) {
            $scope.j = data.data[0].avg_mark;//获取到的数据为Object
          }
          console.log($scope.j);
          //显示时class变化
          $scope.star = document.getElementById("star");
          $scope.star_li = $scope.star.getElementsByTagName("li");
          var i = 0;
          for (i = 0; i < $scope.j; i++) {
            $scope.star_li[i].className = "act";
          }
          for (i = $scope.j; i < $scope.star_li.length; i++) {
            $scope.star_li[i].className = "off";
          }
        }, function (error) {
          console.log(error);
          $rootScope.showToastOrDialog(error.data.msg, function () {
          });
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };


    ///显示停车场评价
    function PComDe(park) {
      $scope.Hot = [];
      $scope.New = [];
      $scope.HotCom = [];
      $scope.NewCom = [];
      $scope.HotComUser = [];
      $scope.NewComUser = [];
      console.log(park.park_id);
      ShowCom(park);
      ShowasTime(park);
      console.log('评论的停车场');
      console.log(park);
      $scope.PComDetailModal.show();
    };

    ///热门评论，根据点赞数目显示评论
    function ShowCom(park) {
      SearchHist.fPraise(park.park_id)
        .then(function (data) {
          data.data.forEach(function (com) {
            $scope.HotCom.push(com);
          })
        }, function (error) {
          console.log(error);
          $rootScope.showToastOrDialog(error.data.msg, function () {
          });
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    }

    //保存停车场评论
    function saveParkCom() {
      $scope.checkbox1 = document.getElementById('check1');
      $scope.checkbox2 = document.getElementById('check2');
      $scope.checkbox3 = document.getElementById('check3');
      $scope.checkbox4 = document.getElementById('check4');
      $scope.checkbox5 = document.getElementById('check5');
      $scope.Content = '';
      if ($scope.checkbox1.checked) {
        $scope.Content += '出入方便 ';
      }
      if ($scope.checkbox2.checked) {
        $scope.Content += '车位充足 ';
      }
      if ($scope.checkbox3.checked) {
        $scope.Content += '环境干净 ';
      }
      if ($scope.checkbox4.checked) {
        $scope.Content += '服务热情 ';
      }
      if ($scope.checkbox5.checked) {
        $scope.Content += '价格适中 ';
      }
      if ($scope.com.content) {
        $scope.Content += $scope.com.content;
      }
      $scope.Time = new Date().getTime();
      SearchHist.PCom($scope.User.user_id, $scope.NowPark.park_id, $scope.Content, $scope.staract, $scope.Time, $scope.User.nick_name)
        .then(function (data) {
          $rootScope.showToastOrDialog('停车场评论成功', function () {
          });
        }, function (error) {
          console.log(error);
          $rootScope.showToastOrDialog(error.data.msg, function () {
          });
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    //增加点赞数目
    $scope.addpraise = function (x) {
      x.praise = x.praise + 1;
      SearchHist.AddPraise(x.user_id, x.park_id)
        .then(function (data) {
          console.log(data);            //获取到的数据为Object
        }, function (error) {
          console.log(error);
          $rootScope.showToastOrDialog(error.data.msg, function () {
          });
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    }

    ///最新评论，以时间顺序显示
    function ShowasTime(park) {
      SearchHist.LatestCom(park.park_id)
        .then(function (data) {
          data.data.forEach(function (com) {
            $scope.NewCom.push(com);
          })
        }, function (error) {
          console.log(error);
          $rootScope.showToastOrDialog(error.data.msg, function () {
          });
        })
        .finally(function () {
          $ionicLoading.hide();
        });
      console.log($scope.NewCom);
    }

    ///跳转到谷歌进行导航
    function GoToGoogle(start, end) {
      var route = ({
        start: start,
        // startLatlng:'',
        end: end,
        //endLatlng:'',
      });

      window.plugins.EPGoogle(route,
        function (data) {
          alert(data);
        },
        function (error) {
          alert(error);
        });
    };

    ///EasyLuck confirmPopup
    function showEasyOrLuck() {
      var confirmPopup = $ionicPopup.confirm({
        title: 'EASY OR LUCK',
        template: 'How about the parking?',
        cancelText: 'LUCK',
        cancelType: 'button-assertive',
        okText: 'EASY',
        okType: 'button-balanced'
      });
      confirmPopup.then(function (res) {
        if (res) {
          console.log('LUCK');
        } else {
          console.log('EASY');
        }
        showShare();
      });
    };

    //分享confirmPopup
    function showShare() {
      var confirmPopup = $ionicPopup.confirm({
        title: 'SHARE',
        template: 'Do you want to share with your friends?',

      });
      confirmPopup.then(function (res) {
        if (res) {
          console.log('share');
        } else {
          console.log('do not share');
        }
        // $location.url('/app/home');
      });
    };

    ///判断是否到达目的地
    function ArrivalOrNot(park) {
      ///监视用户位置变化
      var watchOptions = {
        timeout: 3000,
        enableHighAccuracy: false // may cause errors if true
      };

      var watch = $cordovaGeolocation.watchPosition(watchOptions);
      watch.then(
        null,
        function (err) {
          // error
        },
        function (position) {
          //判断是或否到达停车位附近
          console.log('watch' + position.coords.latitude);
          $scope.latlng = [];
          $scope.latlng = park.location.split(",");
          console.log(park.location);
          if (Math.abs(parseFloat(position.coords.latitude) - parseFloat($scope.latlng[1])) < 0.001 && Math.abs(parseFloat(position.coords.longitude) - parseFloat($scope.latlng[0])) < 0.001) {
            $rootScope.showToastOrDialog('已到达' + park.name + '导航结束', function () {
              watch.clearWatch();
              showEasyOrLuck();
            });
          }
        });
    };

    ///对zoom_changed添加监听事件
    function ZoomChangedListen() {
      $scope.map.addListener('zoom_changed', function () {
        RefreshThreeLevel();

      });
    };

    //日期选择后的回调函数
    var datePickerCallbacks = function (val) {
      console.log('jinru');
      if (typeof (val) === 'undefined') {
      } else {
        console.log('Selected date is : ', val);
        if ($scope.DateType == 'enter') {
          $scope.datepickerObjectEnd.inputEnterDate = val;  //这行官网没有，不设置 的话，选中日期不能回填到页面。
          $scope.ParkOption.EnterData = formatDate(val);
          calculateParkTime();
        } else {
          $scope.ParkOption.LeaveData = formatDate(val);
          $scope.datepickerObjectEnd.inputLeaveDate = val;  //这行官网没有，不设置 的话，选中日期不能回填到页面。
          calculateParkTime();
        }
      }
    };
    ///时间选择器
    $scope.datepickerObjectEnd = {
      titleLabel: '选择日期',  //可选
      todayLabel: '今天',  //可选
      closeLabel: '关闭',  //可选
      setLabel: '设置',  //可选
      setButtonType: 'button-assertive',  //可选
      todayButtonType: 'button-assertive',  //可选
      closeButtonType: 'button-assertive',  //可选
      inputEnterDate: new Date(),  //可选，输入值
      inputLeaveDate: new Date(),  //可选，输入值
      mondayFirst: true,  //可选,星期一开头
      templateType: 'popup', //可选i.e.的模式 modal or popup(兼容模式？)
      showTodayButton: 'true', //可选
      modalHeaderColor: 'bar-positive', //可选
      modalFooterColor: 'bar-positive', //可选
      from: new Date(2008, 8, 2), //可选
      to: new Date(2030, 8, 25),  //可选
      callback: function (val) {  //Mandatory
        datePickerCallbacks(val);
      },
      dateFormat: 'yyyy-MM-dd', //可选
      closeOnSelect: true, //可选,设置选择日期后是否要关掉界面。呵呵，原本是false。
    };

    //计算停车时长
    function calculateParkTime() {
      $scope.ParkOption.Enter = $scope.ParkOption.EnterData + ' ' + $scope.ParkOption.EnterTime;
      $scope.ParkOption.Leave = $scope.ParkOption.LeaveData + ' ' + $scope.ParkOption.LeaveTime;
      $scope.ParkOption.Enter = $scope.ParkOption.Enter.replace(/-/g, "/");
      $scope.ParkOption.Leave = $scope.ParkOption.Leave.replace(/-/g, "/");
      $scope.ParkOption.WholeEnterTime = new Date($scope.ParkOption.Enter);
      $scope.ParkOption.WholeLeaveTime = new Date($scope.ParkOption.Leave);
      calculateTime();
    };

    //计算时间差函数
    function calculateTime() {
      var date3 = $scope.ParkOption.WholeLeaveTime.getTime() - $scope.ParkOption.WholeEnterTime.getTime();
      //计算出相差天数
      var days = Math.floor(date3 / (24 * 3600 * 1000));
      console.log($scope.ParkOption.WholeLeaveTime.getTime());
      //计算出小时数
      var leave1 = date3 % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / (3600 * 1000));
      //计算相差分钟数
      var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / (60 * 1000));
      //计算相差秒数
      var leave3 = leave2 % (60 * 1000);      //计算分钟数后剩余的毫秒数

      $scope.ParkOption.TotalTime = days + "天" + hours + "小时" + minutes + "分钟";
      console.log($scope.ParkOption.TotalTime);
    };

    var formatDate = function (date) {
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? '0' + m : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      return y + '-' + m + '-' + d;
    };

    ///点的形式表示停车场
    function drawPoint(parks, image, label) {
      //console.log(parks);
      if (label) {
        parks.forEach(function (data) {
          $scope.latlng = [];
          $scope.latlng = data.location.split(",");

          $scope.position = new google.maps.LatLng(parseFloat($scope.latlng[1]), parseFloat($scope.latlng[0]));
          $scope.marker = new google.maps.Marker({
            position: $scope.position,
            map: $scope.map,
            //title: data.priceShow.split('$')[1],
            icon: image,
          });

          //$scope.marker1=new google.maps.InfoWindow({
          //  content: '12'
          //});
          //$scope.marker1.open($scope.map, $scope.marker);
          $scope.marker.addListener('click', function () {
            showParkBrief(data.name);
          });
          $scope.NearPark.markers.push($scope.marker);
          $scope.marker.setMap($scope.map);
          //$scope.marker1.setMap($scope.map);

          $scope.overLay=new TxtOverlay($scope.position, '$'+data.price,"customBox",$scope.map);
          $scope.NearPark.markers.push($scope.overLay);

        });
      } else {
        parks.forEach(function (data) {
          $scope.latlng = [];
          $scope.latlng = data.location.split(",");
          $scope.marker = new google.maps.Marker({
            position: {lat: parseFloat($scope.latlng[1]), lng: parseFloat($scope.latlng[0])},
            map: $scope.map,
            icon: image,
          });
          $scope.marker.addListener('click', function () {
            showParkBrief(data.name);
          });
          $scope.NearPark.markers.push($scope.marker);
          $scope.marker.setMap($scope.map);
        });
      }

    };

    //画虚线
    function drawBrokenLine(name,LatlngList){
      $scope.latlngInterval=0.00006;
      for(var i=0;i<LatlngList.length-1;i++){
        //起点
        $scope.drawLatAndLng = LatlngList[i].split(' ');
        if(i==0){
          $scope.drawLatlng1 = {
            lat: parseFloat($scope.drawLatAndLng[1]),
            lng: parseFloat($scope.drawLatAndLng[0])
          };
        }else{
          $scope.drawLatlng1 = {
            lat: parseFloat($scope.drawLatAndLng[2]),
            lng: parseFloat($scope.drawLatAndLng[1])
          };
        }
        //终点
        $scope.drawLatAndLng = LatlngList[i+1].split(' ');
        $scope.drawLatlng2 = {
          lat: parseFloat($scope.drawLatAndLng[2]),
          lng: parseFloat($scope.drawLatAndLng[1])
        };

        //按间隔进行分割
        var n=parseInt(($scope.drawLatlng2.lng-$scope.drawLatlng1.lng)/$scope.latlngInterval);

        for(var j=0;j<n;j=j+2){
          $scope.draw1={lat:($scope.drawLatlng1.lat*(n-j-1)/n)+($scope.drawLatlng2.lat/n*(j+1))
            ,lng:($scope.drawLatlng1.lng*(n-j-1)/n)+($scope.drawLatlng2.lng/n*(j+1))};

          $scope.draw2={lat:($scope.drawLatlng1.lat*(n-j-2)/n)+($scope.drawLatlng2.lat/n*(j+2))
            ,lng:($scope.drawLatlng1.lng*(n-j-2)/n)+($scope.drawLatlng2.lng/n*(j+2))};

          $scope.drawPolyline=[$scope.draw1,$scope.draw2];

          $scope.drawshape = new google.maps.Polyline({
            path: $scope.drawPolyline,
            geodesic: true,
            strokeColor: 'orange',
            strokeOpacity: 1.0,
            strokeWeight: 4
          });
          $scope.drawshape.addListener('click', function () {
            showParkBrief(name);
          });
          $scope.NearPark.markers.push($scope.drawshape);
          $scope.drawshape.setMap($scope.map);
        }
      };
    };

    ///街边停车场以线的形式表示，非街边停车场以面的形式表示
    function drawParkLot(parks, type, color) {
      if (type == 'Polyline') {
        parks.forEach(function (data) {
          if (data.geometry) {
            $scope.EachPark = [];
            $scope.NearPark.draw = [];
            $scope.parkGeometry = [];
            $scope.parkGeometry = data.geometry.split('(');
            $scope.parkDraw = $scope.parkGeometry[2];
            $scope.drawLatlng = $scope.parkDraw.split(',');
            $scope.parkflag = 1;
            if(color=='orange'){//permit
              //TODO
              drawBrokenLine(data.name,$scope.drawLatlng);
            }else{
              $scope.drawLatlng.forEach(function (latlng) {
                $scope.drawLatAndLng = latlng.split(' ');
                if ($scope.parkflag) {
                  $scope.drawParkLine = {
                    lat: parseFloat($scope.drawLatAndLng[1]),
                    lng: parseFloat($scope.drawLatAndLng[0])
                  };
                  $scope.parkflag = 0;
                }
                else {
                  $scope.drawParkLine = {
                    lat: parseFloat($scope.drawLatAndLng[2]),
                    lng: parseFloat($scope.drawLatAndLng[1])
                  };
                }
                $scope.EachPark.push($scope.drawParkLine);
              });
              $scope.drawshape = new google.maps.Polyline({
                path: $scope.EachPark,
                geodesic: true,
                strokeColor: color,
                strokeOpacity: 1.0,
                strokeWeight: 4
              });
              $scope.drawshape.addListener('click', function () {
                showParkBrief(data.name);
              });
              $scope.NearPark.markers.push($scope.drawshape);
              $scope.drawshape.setMap($scope.map);
            }

          }
        });
      } else if (type == 'Polygon') {
        parks.forEach(function (data) {
          if (data.geometry) {
            $scope.EachPark = [];
            $scope.NearPark.draw = [];
            $scope.parkGeometry = [];
            $scope.parkGeometry = data.geometry.split('(');
            $scope.drawtype = 'polygon';
            $scope.parkDraw = $scope.parkGeometry[3].split(')')[0];
            $scope.drawLatlng = $scope.parkDraw.split(',');
            $scope.parkflag = 1;
            $scope.drawLatlng.forEach(function (latlng) {
              $scope.drawLatAndLng = latlng.split(' ');
              if ($scope.parkflag) {
                $scope.drawParkLine = {
                  lat: parseFloat($scope.drawLatAndLng[1]),
                  lng: parseFloat($scope.drawLatAndLng[0])
                };
                $scope.parkflag = 0;
              }
              else {
                $scope.drawParkLine = {
                  lat: parseFloat($scope.drawLatAndLng[2]),
                  lng: parseFloat($scope.drawLatAndLng[1])
                };
              }
              $scope.EachPark.push($scope.drawParkLine);
            });

            $scope.drawshape = new google.maps.Polygon({
              paths: $scope.EachPark,
              strokeColor: '#1E3DA1',
              strokeOpacity: 0.9,
              strokeWeight: 2,
              fillColor: '#1E3DA1',
              fillOpacity: 0.5
            });
            $scope.drawshape.addListener('click', function () {
              showParkBrief(data.name);
            });
            $scope.NearPark.markers.push($scope.drawshape);
            $scope.drawshape.setMap($scope.map);
          }
        })
      }
    };

    ///街边停车场画出停车位
    function drawParkSpace(parks) {
      parks.forEach(function (parkSpace) {
        $scope.latlng = [];
        $scope.latlng = parkSpace.location.split(',');
        var interval = 0.00001;
        $scope.EachParkSpace = [{
          lat: parseFloat($scope.latlng[1]) + interval / 2,
          lng: parseFloat($scope.latlng[0]) - interval
        },
          {lat: parseFloat($scope.latlng[1]) + interval / 2, lng: parseFloat($scope.latlng[0]) + interval},
          {lat: parseFloat($scope.latlng[1]) - interval / 2, lng: parseFloat($scope.latlng[0]) + interval},
          {lat: parseFloat($scope.latlng[1]) - interval / 2, lng: parseFloat($scope.latlng[0]) - interval}];
        $scope.drawshape = new google.maps.Polygon({
          paths: $scope.EachParkSpace,
          strokeColor: 'yellow',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: 'yellow',
          fillOpacity: 0.35
        });
        $scope.drawshape.setMap($scope.map);
        $scope.NearPark.markers.push($scope.drawshape);
      })
    };

    ///画停车场出入口
    function drawParkEntity(parks) {
      console.log('entity');
      console.log(parks);

      parks.forEach(function (parkEntity) {
        if (parkEntity.entity_type == '出口') {
          $scope.image = {
            url: 'img/out.png',
            // This marker is 20 pixels wide by 32 pixels high.
            size: new google.maps.Size(40, 30.4),
            // The origin for this image is (0, 0).
            origin: new google.maps.Point(0, 0),
            // The anchor for this image is the base of the flagpole at (0, 32).
            anchor: new google.maps.Point(0, 32)
          };
        } else if (parkEntity.entity_type == '入口') {
          $scope.image = {
            url: 'img/in.png',
            // This marker is 20 pixels wide by 32 pixels high.
            size: new google.maps.Size(40, 30.4),
            // The origin for this image is (0, 0).
            origin: new google.maps.Point(0, 0),
            // The anchor for this image is the base of the flagpole at (0, 32).
            anchor: new google.maps.Point(0, 32)
          };
        }
        $scope.latlng = [];
        $scope.latlng = parkEntity.location.split(',');
        $scope.marker = new google.maps.Marker({
          position: {lat: parseFloat($scope.latlng[1]), lng: parseFloat($scope.latlng[0])},
          map: $scope.map,
          icon: $scope.image,
        });
        $scope.marker.setMap($scope.map);
        $scope.NearPark.markers.push($scope.marker);
      });
    };

    //获取一般停车场收费数据
    function getOffStreetCharge(parkID) {
      SearchHist.getOffParkCharge(parkID)
        .then(function (data) {
          data.data.forEach(function (charge_rule) {
            $scope.NearPark.Off.Charge.push(charge_rule);
          });
        }, function (error) {
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    function getOffStreetChargeRule(parkID) {
      $scope.ParkPrice.ChargeList = [];
      $scope.NearPark.Off.Charge.forEach(function (chargeRule) {
        if (chargeRule.park_ID == parkID) {
          $scope.ParkPrice.ChargeList.push(chargeRule.rule_describe);
        }
      });
    };

    //获取街边停车场收费数据
    function getOnStreetCharge(park) {
      SearchHist.getOnParkCharge(park.park_id)
        .then(function (data) {
          $scope.NearPark.On.Charge.push(data.data[0]);
          $scope.ParkPrice.Charge = data.data[0];
        }, function (error) {
          //console.log(error);
          //$rootScope.showToastOrDialog(error.data.msg, function () {
          //});
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    function getOnStreetChargeRule(park) {
      $scope.ParkPrice.ChargeList = [];
      $scope.NearPark.On.Charge.forEach(function (chargeRule) {
        if (chargeRule.park_id == park.park_id) {
          StandardPrice(park, chargeRule);
        }
      });
    };

    ///获取街边停车场的停车位数据
    function getParkSpace(parkID) {
      SearchHist.getOnParkSpace(parkID)
        .then(function (data) {
          data.data.forEach(function (parkSpace) {
            $scope.NearPark.On.ParkSpace.push(parkSpace);
          })
        }, function (error) {
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    ///获取非街边停车场的内部实体数据
    function getParkEntity(parkID) {
      SearchHist.getOffParkEntity(parkID)
        .then(function (data) {
          data.data.forEach(function (parkEntity) {
            $scope.NearPark.Off.ParkEntity.push(parkEntity);
          })
        }, function (error) {
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    //获取停车场的动态信息
    function getParkDifficulty(park) {
      SearchHist.getDifficulty(park.park_id)
        .then(function (data) {
          if (data.data[0].difficulty == 'easy') {
            $scope.NearPark.On.Easy.push(park);
          } else if (data.data[0].difficulty == 'middle') {
            $scope.NearPark.On.Middle.push(park);
          } else if (data.data[0].difficulty == 'difficult') {
            $scope.NearPark.On.Difficult.push(park);
          }
        }, function (error) {
        })
        .finally(function () {
          $ionicLoading.hide();
        });
    };

    //收费价格
    function StandardPrice(park, rule) {
      // price time time_unit
      $scope.onStreet = {};

      park.limit_hour = rule.hours;
      park.ChargeList = [];
      $scope.ParkPrice.Charge = [];
      $scope.ParkPrice = [];
      $scope.str = rule.price;
     // console.log($scope.str);
      $scope.ParkPrice.ChargeList = $scope.str.split('}');
      for (var i = 0; i < $scope.ParkPrice.ChargeList.length - 1; i++) {
        $scope.ParkPrice.ChargeList[i] = $scope.ParkPrice.ChargeList[i].split('{')[1];
        $scope.onStreet.price = $scope.ParkPrice.ChargeList[i].split('/')[0];
        if ($scope.ParkPrice.ChargeList[i].indexOf('min') > -1) {
          $scope.onStreet.time = $scope.ParkPrice.ChargeList[i].split('/')[1].split('min')[0];
          $scope.onStreet.time_unit = 'min';
        } else if ($scope.ParkPrice.ChargeList[i].indexOf('hour') > -1) {
          $scope.onStreet.time = $scope.ParkPrice.ChargeList[i].split('/')[1].split('hour')[0];
          $scope.onStreet.time_unit = 'hour';
        } else if ($scope.ParkPrice.ChargeList[i].indexOf('max') > -1) {
          $scope.onStreet.time = 1;
          $scope.onStreet.time_unit = 'max';
        }
        park.ChargeList.push($scope.onStreet);
      }
      //console.log('街边');
      //console.log(park.limit_hour);
      //console.log(park.ChargeList);
    }


    //停车场归类
    function ReclassParks(parks) {
      $scope.NearPark.Off.Charge = [];
      $scope.NearPark.On.Charge = [];

      parks.forEach(function (park) {
        park.distance = $scope.distance($scope.SearchPlace.lat, $scope.SearchPlace.lng, parseFloat(park.location.split(',')[1]), parseFloat(park.location.split(',')[0]));
        park.price=0;
        park.priceShow='$'+park.price;
      });
      //默认按价格排序
      //parks.sort(function(a,b){
      //  return a.price- b.price||parks.indexOf(a)-parks.indexOf(b);
      //});
      parks.forEach(function (park) {
        if (park.type == 'Parking Meter') {
          $scope.NearPark.On.Parks.push(park);
        } else {
          $scope.NearPark.Off.Parks.push(park);
        }
      });
      $scope.NearPark.On.Parks.forEach(function (park) {
        getParkDifficulty(park);
        getParkSpace(park.park_id);
        getOnStreetCharge(park);
      });
      $scope.NearPark.Off.Parks.forEach(function (park) {
        getParkEntity(park.park_id);
        getOffStreetCharge(park.park_id);
      });
      CopyNearParks();
    };

    ///停车场筛选
    function FilteParks() {

      $scope.week = {
        Mon: 1,
        Tues: 2,
        Wed: 3,
        Thur: 4,
        Fri: 5,
        Sat: 6,
        Sun: 7
      };

      $scope.enter = new Date($scope.UserSet.EnterTime.split(' ')[0]).getDay();
      if ($scope.enter == 0) {
        $scope.enter = 7;
      }
      $scope.leave = new Date($scope.UserSet.LeaveTime.split(' ')[0]).getDay();
      if ($scope.leave == 0) {
        $scope.leave = 7;
      }
      console.log('星期：' + $scope.leave);

      $scope.NearPark.Parks.forEach(function (park) {
        if (park.biz_hour) {
          $scope.biz = park.biz_hour.split(',');
          if ($scope.biz[0].indexOf('-') > 0) {
            $scope.weekday = $scope.biz[0].split('-');
            $scope.weekday[0] = $scope.weekday[0].split('"')[1];
            $scope.weekday[1] = $scope.weekday[1].split('"')[0];
          } else {
            $scope.weekday[0] = $scope.biz[0].split('"')[1];
            $scope.weekday[1] = $scope.biz[0].split('"')[1];
          }

          if ($scope.biz[1].indexOf('-') > 0) {
            $scope.daytime = $scope.biz[1].split('-');
            $scope.daytime[0] = $scope.daytime[0].split('"')[1];
            $scope.daytime[1] = $scope.daytime[1].split('"')[0];
          } else {
            $scope.daytime = $scope.biz[1].split('"')[1];
          }

          //console.log($scope.enter+'-'+$scope.leave+'-'+$scope.week[$scope.weekday[0]]+'-'+$scope.week[$scope.weekday[1]]);

          //进出时间均在区间内
          if ($scope.enter >= $scope.week[$scope.weekday[0]]
            && $scope.enter <= $scope.week[$scope.weekday[1]]
            && $scope.leave >= $scope.week[$scope.weekday[0]]
            && $scope.leave <= $scope.week[$scope.weekday[1]]) {
            if ($scope.daytime == '24 hours') {
              $scope.NearPark.Filter.Parks.push(park);
              if (park.type == 'Parking Meter') {
                $scope.NearPark.Filter.OnParks.push(park);
                $scope.NearPark.On.Easy.forEach(function (easyPark) {
                  if (easyPark.park_id == park.park_id) {
                    $scope.NearPark.Filter.Easy.push(park);
                  }
                });
                $scope.NearPark.On.Middle.forEach(function (easyPark) {
                  if (easyPark.park_id == park.park_id) {
                    $scope.NearPark.Filter.Middle.push(park);
                  }
                });
                $scope.NearPark.On.Difficult.forEach(function (easyPark) {
                  if (easyPark.park_id == park.park_id) {
                    $scope.NearPark.Filter.Difficult.push(park);
                  }
                });
              } else {
                $scope.NearPark.Filter.OffParks.push(park);
              }
              $scope.NearPark.Off.ParkEntity.forEach(function (parkEntity) {

                if (park.park_id == parkEntity.park_id) {
                  $scope.NearPark.Filter.ParkEntity.push(parkEntity);
                }
              });
            } else {

              $scope.entertime = $scope.UserSet.EnterTime.split(' ')[1].split(':');
              $scope.leavetime = $scope.UserSet.LeaveTime.split(' ')[1].split(':');
              // console.log($scope.entertime[0]+'-'+$scope.leavetime[0]+'-'+$scope.daytime[0].split(':')[0]+'-'+$scope.daytime[1].split(':')[0]);

              if ($scope.enter == $scope.leave) {
                if ($scope.time_range($scope.daytime[0], $scope.daytime[1], $scope.UserSet.EnterTime.split(' ')[1])
                  && $scope.time_range($scope.daytime[0], $scope.daytime[1], $scope.UserSet.LeaveTime.split(' ')[1])) {

                  $scope.NearPark.Filter.Parks.push(park);
                  if (park.type == 'Parking Meter') {
                    $scope.NearPark.Filter.OnParks.push(park);
                    $scope.NearPark.On.Easy.forEach(function (easyPark) {
                      if (easyPark.park_id == park.park_id) {
                        $scope.NearPark.Filter.Easy.push(park);
                      }
                    });
                    $scope.NearPark.On.Middle.forEach(function (easyPark) {
                      if (easyPark.park_id == park.park_id) {
                        $scope.NearPark.Filter.Middle.push(park);
                      }
                    });
                    $scope.NearPark.On.Difficult.forEach(function (easyPark) {
                      if (easyPark.park_id == park.park_id) {
                        $scope.NearPark.Filter.Difficult.push(park);
                      }
                    });
                  } else {
                    $scope.NearPark.Filter.OffParks.push(park);
                  }
                  $scope.NearPark.Off.ParkEntity.forEach(function (parkEntity) {

                    if (park.park_id == parkEntity.park_id) {
                      $scope.NearPark.Filter.ParkEntity.push(parkEntity);
                    }
                  });
                }
              }
            }
          }
        }
      });

      if ($scope.UserSet.ParkType == 10) {
        $scope.NearPark.Filter.Parks = $scope.NearPark.Filter.OnParks;
        $scope.NearPark.Filter.OffParks = [];
        $scope.NearPark.Filter.ParkEntity = [];
      } else if ($scope.UserSet.ParkType == 1) {
        $scope.NearPark.Filter.Parks = $scope.NearPark.Filter.OffParks;
        $scope.NearPark.Filter.OnParks = [];
        $scope.NearPark.Filter.Easy = [];
        $scope.NearPark.Filter.Middle = [];
        $scope.NearPark.Filter.Difficult = [];
      }
      if ($scope.NearPark.Filter.OffParks.length > 0) {
        $scope.NearPark.Filter.OffParks.forEach(function (park) {
          park.PriceList = [];
          $scope.NearPark.Off.Charge.forEach(function (charge) {
            if (charge.park_ID == park.park_id) {
              park.PriceList.push(charge);
            }
          });
          caculateOffPrice(park, $scope.enter, $scope.leave, $scope.entertime, $scope.leavetime, $scope.UserSet.TotalTime);
        });
      }
      ;
      if ($scope.NearPark.Filter.OnParks.length > 0) {
        $scope.NearPark.Filter.OnParks.forEach(function (onStreetPark) {
          getOnStreetChargeRule(onStreetPark);
          caculateOnPrice(onStreetPark, $scope.UserSet.TotalTime);
        });
      }
      ;
      RefreshThreeLevel();
    };

    //刷新三级显示
    function RefreshThreeLevel() {
      if ($scope.NearPark.Filter.Parks) {
        if ($scope.map.getZoom() == 17) {
          $scope.NearPark.markers.forEach(function (data) {
            data.setMap(null);
          });
          addAdoptMarker('2');
        }
        if ($scope.map.getZoom() == 16) {
          $scope.NearPark.markers.forEach(function (data) {
            data.setMap(null);
          });
          addAdoptMarker('1');
        } else if ($scope.map.getZoom() <= 15 && $scope.map.getZoom() >= 12) {
          $scope.NearPark.markers.forEach(function (data) {
            data.setMap(null);
          });
          addAdoptMarker('0');
        } else if ($scope.map.getZoom() == 11) {
          $scope.NearPark.markers.forEach(function (data) {
            data.setMap(null);
          });
        }
      }
    }

    //初始化Filter中的数据
    function initFilterParks() {
      //初始化filter
      $scope.NearPark.Filter.Parks = [];
      $scope.NearPark.Filter.OnParks = [];
      $scope.NearPark.Filter.OffParks = [];
      $scope.NearPark.Filter.Easy = [];
      $scope.NearPark.Filter.Middle = [];
      $scope.NearPark.Filter.Difficult = [];
      $scope.NearPark.Filter.ParkSpace = [];
      $scope.NearPark.Filter.ParkEntity = [];
    };

    //初始化NearPark.Parks中的数据
    function initNearParks() {
      $scope.NearPark.Parks = [];
      $scope.NearPark.On.Parks = [];
      $scope.NearPark.Off.Parks = [];
      $scope.NearPark.On.Easy = [];
      $scope.NearPark.On.Middle = [];
      $scope.NearPark.On.Difficult = [];
      $scope.NearPark.On.ParkSpace = [];
      $scope.NearPark.Off.ParkEntity = [];
    };

    //Filter中的初始数据为NearPark.Parks中的数据
    function CopyNearParks() {
      console.log('copy');
      $scope.NearPark.Filter.Parks = $scope.NearPark.Parks;
      $scope.NearPark.Filter.OnParks = $scope.NearPark.On.Parks;
      $scope.NearPark.Filter.OffParks = $scope.NearPark.Off.Parks;
      $scope.NearPark.Filter.Easy = $scope.NearPark.On.Easy;
      $scope.NearPark.Filter.Middle = $scope.NearPark.On.Middle;
      $scope.NearPark.Filter.Difficult = $scope.NearPark.On.Difficult;
      $scope.NearPark.Filter.ParkSpace = $scope.NearPark.On.ParkSpace;
      $scope.NearPark.Filter.ParkEntity = $scope.NearPark.Off.ParkEntity;
    }

    //判断时间点是否在时间范围内
    $scope.time_range = function (beginTime, endTime, nowTime) {
      var strb = beginTime.split(":");
      if (strb.length != 2) {
        return false;
      }

      var stre = endTime.split(":");
      if (stre.length != 2) {
        return false;
      }

      var strn = nowTime.split(":");
      if (stre.length != 2) {
        return false;
      }
      var b = new Date();
      var e = new Date();
      var n = new Date();

      b.setHours(strb[0]);
      b.setMinutes(strb[1]);
      e.setHours(stre[0]);
      e.setMinutes(stre[1]);
      n.setHours(strn[0]);
      n.setMinutes(strn[1]);

      if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
        return true;
      } else {
       // console.log("当前时间是：" + n.getHours() + ":" + n.getMinutes() + "，不在该时间范围内！");
        return false;
      }
    };

    //计算用户到停车场的距离
    $scope.distance = function getDistance(lat1, lng1, lat2, lng2) {

      var EARTH_RADIUS = 6378137.0; //单位M
      var f = getRad((lat1 + lat2) / 2);
      var g = getRad((lat1 - lat2) / 2);
      var l = getRad((lng1 - lng2) / 2);

      var sg = Math.sin(g);
      var sl = Math.sin(l);
      var sf = Math.sin(f);

      var s, c, w, r, d, h1, h2;
      var a = EARTH_RADIUS;
      var fl = 1 / 298.257;

      sg = sg * sg;
      sl = sl * sl;
      sf = sf * sf;

      s = sg * (1 - sl) + (1 - sf) * sl;
      c = (1 - sg) * (1 - sl) + sf * sl;

      w = Math.atan(Math.sqrt(s / c));
      r = Math.sqrt(s * c) / w;
      d = 2 * w * a;
      h1 = (3 * r - 1) / 2 / c;
      h2 = (3 * r + 1) / 2 / s;
      return (d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg)) / 1609.344).toFixed(2);
    };

    function getRad(d) {
      var PI = Math.PI;
      return d * PI / 180.0;
    };

    ///比较大小
    function compare(propertyName) {
      return function (object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];
        if (value2 < value1) {
          return -1;
        }
        else if (value2 > value1) {
          return 1;
        }
        else {
          return 0;
        }
      }
    };

    ///计算街边停车场收费
    function caculateOnPrice(park, totalTime) {

      //console.log('限停');
      //console.log(park.limit_hour);
      //console.log(park.ChargeList);

      //用户停车时间
      $scope.parktime[0] = parseInt(totalTime.split('天')[0]);
      $scope.parktime[1] = parseInt(totalTime.split('天')[1].split('小时')[0]) + $scope.parktime[0] * 24;
      $scope.parktime[2] = parseInt(totalTime.split('天')[1].split('小时')[1].split('分钟')[0]);

      if ($scope.parktime[2] > 0) {
        $scope.parktime[1]++;
      }

      if ($scope.parktime[1] > parseInt(park.limit_hour)) {
        park.price = $scope.Max;
        park.priceShow = '限停' + park.limit_hour + '小时，超出限停时间';
      } else {
        $scope.onStreetFlag = 0;
        for (var i = 0; i < park.ChargeList.length && !$scope.onStreetFlag; i++) {
          if ($scope.parktime[1] == 0) {//停车时间小于1小时
            if (park.ChargeList[i].time_unit == 'min') {//在min规则中找合适的收费
              if ($scope.parktime[2] <= parseInt(park.ChargeList[i].time)) {
                park.priceShow = park.ChargeList[i].price;
                park.price = park.priceShow.split('$')[1];
                $scope.onStreetFlag = 1;
              }
            } else if (!$scope.onStreetFlag) {//没找到，需要按小时收费
              park.priceShow = park.ChargeList[i].price;
              park.price = park.priceShow.split('$')[1];
              $scope.onStreetFlag = 1;
            }
          } else {
            if (park.ChargeList[i].time_unit == 'hour') {
              if ($scope.parktime[1] < parseInt(park.ChargeList[i].time)
                ||$scope.parktime[1] == parseInt(park.ChargeList[i].time)&&$scope.parktime[2] == 0) {
                park.priceShow = park.ChargeList[i].price;
                park.price = park.priceShow.split('$')[1];
                $scope.onStreetFlag = 1;
              }
            }else if(!$scope.onStreetFlag){
              if(park.ChargeList[i].time_unit == 'max'){
                park.priceShow = park.ChargeList[i].price;
                park.price = park.priceShow.split('$')[1];
                $scope.onStreetFlag = 1;
              }
            }

          }
        }
      }
    }

    ///计算停车场收费
    function caculateOffPrice(park, enterDay, leaveDay, enterTime, leaveTime, totalTime) {
      park.price=0;
      park.priceShow='$'+park.price;
      console.log('计算' + totalTime);
      $scope.CommonPrice = []; //普通收费规则，包括each max common
      $scope.SpecialPrice = [];  //特殊收费规则
      $scope.findPrice = 0;  //是否有满足条件的特殊收费规则

      park.PriceList.forEach(function (eachPrice) {
        if (eachPrice.rule_name == 'common' || eachPrice.rule_name == 'each' || eachPrice.rule_name == 'max') {
          $scope.CommonPrice.push(eachPrice);
        } else if (eachPrice.rule_name != 'event') {//暂时不考虑特殊事件
          $scope.SpecialPrice.push(eachPrice);
        }
      });
      $scope.SpecialPrice.forEach(function (price) {
        $scope.startFlag = 0;
        $scope.endFlag = 0;
        //判断满足哪条规则

        //console.log('判断进出日期');
        //console.log(enterDay);
        //console.log(leaveDay);
        //
        //console.log($scope.week[price.rule_start_day]);
        //console.log($scope.week[price.rule_end_day]);

        if ((price.rule_start_day == 'all' || enterDay >= $scope.week[price.rule_start_day] && leaveDay >= $scope.week[price.rule_start_day])
          && (price.rule_end_day == 'all' || enterDay <= $scope.week[price.rule_end_day] && leaveDay <= $scope.week[price.rule_end_day])) {
          if (price.rule_start_time == 'all' && price.rule_end_time == 'all') {
            park.price = price.price;
          } else {
            //在开始时间之后
            //console.log('规则');
            //console.log(price);
            if (price.rule_start_time.indexOf('-') > -1 && inTimeRange(enterTime, price.rule_start_time)) {
              $scope.startFlag = 1;
            } else {
              if (price.rule_start_time.indexOf('pm') > -1) {
                $scope.rule_start_time = parseInt(price.rule_start_time.split('pm')[0]) + 12;
              } else {
                $scope.rule_start_time = parseInt(price.rule_start_time.split('am')[0]);
              }
              if (enterTime[0] >= $scope.rule_start_time && leaveTime[0] >= $scope.rule_start_time) {
                $scope.startFlag = 1;
              }
            }

            //在结束时间之前
            if (price.rule_end_time.indexOf('-') > -1 && inTimeRange(enterTime, price.rule_end_time)) {
              $scope.endFlag = 1;
            } else {
              if (price.rule_end_time.indexOf('pm') > -1) {
                //转换为24小时计时
                $scope.rule_end_time = parseInt(price.rule_end_time.split('pm')[0]) + 12;
              } else {
                $scope.rule_end_time = parseInt(price.rule_end_time.split('am')[0]);
              }
              //规则结束时间和开始时间不在同一天
              if ($scope.rule_start_time && $scope.rule_end_time && $scope.rule_end_time <= $scope.rule_start_time) {
                $scope.rule_end_time += 24;
              }
              //进出停车场时间不在同一天
              if (enterDay != leaveDay) {
                leaveTime[0] += 24;
              }
              if (enterTime[0] < $scope.rule_end_time
                && (leaveTime[0] < $scope.rule_end_time || leaveTime[0] == $scope.rule_end_time && leaveTime[1] == '00')) {
                $scope.endFlag = 1;
              }
            }

            //进出时间均在开始结束时间范围之内，符合规则
            if ($scope.startFlag && $scope.endFlag) {
              park.price = price.price;
              $scope.findPrice = 1;
            }
          }
          ;
        }
      });

      //如果没有满足的规则，直接按时间计算价钱
      if (!$scope.findPrice) {

        //用户停车时间
        $scope.parktime = [];
        $scope.dayPrice = 0;
        $scope.hourPrice = 0;
        $scope.minPrice = 0;

        $scope.monthRule = [];
        $scope.dayRule = [];
        $scope.hourRule = [];
        $scope.minRule = [];
        $scope.eachRule = [];
        $scope.maxRule = [];

        //用户停车时间
        $scope.parktime[0] = parseInt(totalTime.split('天')[0]);
        $scope.parktime[1] = parseInt(totalTime.split('天')[1].split('小时')[0]);
        $scope.parktime[2] = parseInt(totalTime.split('天')[1].split('小时')[1].split('分钟')[0]);

        $scope.CommonPrice.forEach(function (price) {
          if (price.rule_name == 'max') {
            $scope.maxRule.push(price);
          } else if (price.rule_name == 'each') {
            $scope.eachRule.push(price);
          } else if (price.time_unit == 'month') {
            $scope.monthRule.push(price);
          } else if (price.time_unit == 'day') {
            $scope.dayRule.push(price);
          } else if (price.time_unit == 'hour') {
            $scope.hourRule.push(price);
          } else if (price.time_unit == 'min') {
            $scope.minRule.push(price);
          }
        });

        //停车超过一天
        if ($scope.parktime[0] != 0) {
          if ($scope.dayRule.length > 0) {
            $scope.dayPrice = parseFloat($scope.dayRule[0].price) * $scope.parktime[0];
          } else {
            $scope.parktime[1] += $scope.parktime[0] * 24;
          }
        }
        ;
        //小时全部换算为分
        if ($scope.parktime[1] != 0) {
          $scope.parktime[2] += $scope.parktime[1] * 60;
        }
        ;

        if ($scope.parktime[2] != 0) {
          $scope.minFlag = 0;
          for (var i = 0; i < $scope.minRule.length && !$scope.minFlag; i++) {
            //此处注意：数据库中收费规则按时间长短来排，否则需要加上判断
            if (parseInt($scope.minRule[i].rule_time) >= $scope.parktime[2]) {
              $scope.minFlag = 1;
              $scope.minPrice = parseFloat($scope.minRule[i].price);
            }
          }
          ;
          //minRule中没有满足的条件，在eachRule中选择合适的时间段进行计算
          if (!$scope.minFlag) {
            $scope.maxTime = 0;
            if ($scope.eachRule.length > 0) {
              $scope.eachRule.forEach(function (eachRule) {
                if (eachRule.rule_time > $scope.maxTime && $eachRule.rule_time <= $scope.parktime[2]) {
                  $scope.minPrice = Math.ceil($scope.parktime[2] / parseFloat(eachRule.rule_time)) * parseFloat(eachRule.price);
                }
              });
            }
          }
          ;
        }

        //判断每天计算收费是否大于max
        park.price = $scope.dayPrice + $scope.minPrice;
        if ($scope.maxRule.length > 0 && (parseFloat($scope.maxRule[0].price) < $scope.minPrice || !park.price)) {
          if ($scope.parktime[0] > 0) {
            park.price = $scope.parktime[0] * parseFloat($scope.maxRule[0].price);
          }
          if ($scope.parktime[2] > 0) {
            park.price += parseFloat($scope.maxRule[0].price);
          }
        }
      }
      park.priceShow = '$' + park.price;
    };

    //判断是否在时间段中
    function inTimeRange(time, timeRange) {
      $scope.times = [];
      $scope.times = timeRange.split('-');
      for (var i = 0; i < $scope.times.length; i++) {
        if ($scope.times[i].indexOf('pm')) {
          $scope.times[i] = parseInt($scope.times[i].split('pm')[0]) + 12;
        } else {
          $scope.times[i] = parseInt($scope.times[i].split('am')[0]);

        }
      }
      if (time[0] >= $scope.times[0] && (time[0] == $scope.times[1] && time[1] == '00' || time[0] < $scope.times[1])) {
        return 1;
      } else {
        return 0;
      }
    };


    //文字图标
    function TxtOverlay(pos, txt, cls, map) {

      // Now initialize all properties.
      this.pos = pos;
      this.txt_ = txt;
      this.cls_ = cls;
      this.map_ = map;
      // We define a property to hold the image's
      // div. We'll actually create this div
      // upon receipt of the add() method so we'll
      // leave it null for now.
      this.div_ = null;
      // Explicitly call setMap() on this overlay
      this.setMap(this.map_);
    }

    TxtOverlay.prototype = new google.maps.OverlayView();

    TxtOverlay.prototype.onAdd = function () {
      // Note: an overlay's receipt of onAdd() indicates that
      // the map's panes are now available for attaching
      // the overlay to the map via the DOM.
      // Create the DIV and set some basic attributes.
      var div = document.createElement('DIV');
      div.className = this.cls_;
      div.style.border = "none";
      div.style.borderWidth = "0px";
      div.style.position = "absolute";
      div.style.cursor = "hand";
      div.innerHTML = this.txt_;
      // Set the overlay's div_ property to this DIV

      this.div_ = div;

      // We add an overlay to a map via one of the map's panes.
      var panes = this.getPanes();
      panes.floatPane.appendChild(div);
    }

    TxtOverlay.prototype.draw = function () {
      var overlayProjection = this.getProjection();
     // console.log('projection');
      var pxPosition = overlayProjection.fromLatLngToDivPixel(this.pos);
      //console.log(pxPosition);

      var div = this.div_;
      div.style.color='red';
      div.style.left = pxPosition.x+5 + 'px';
      div.style.top = pxPosition.y -28+ 'px';

    }

    //Optional: helper methods for removing and toggling the text overlay.  
    TxtOverlay.prototype.onRemove = function () {
      this.div_.parentNode.removeChild(this.div_);
      this.div_ = null;
    }

    TxtOverlay.prototype.toggleDOM = function() {
      if (this.getMap()) {
        this.setMap(null);
      } else {
        this.setMap(this.map_);
      }
    }
  });
